package com.cloud.api.gateway.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class AccessFilter extends ZuulFilter {

	private static Logger logger=LoggerFactory.getLogger(AccessFilter.class);
	@Override
	public Object run() {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		
		logger.info("send {} request to {}",request.getMethod()
				,request.getRequestURL().toString());
		Object accessToken=request.getParameter("accessToken");
		if(null==accessToken)
		{
			logger.warn("accessToken  is empty...");
			currentContext.setSendZuulResponse(false);
			currentContext.setResponseStatusCode(401);
			return null;
		}
		logger.info("tocken is ok..");
		return null;
	}
	/**
	 * 判断该过滤器是否执行
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}
	/**
	 * 过滤器的执行顺序。当请求在一个阶段存在多个过滤器时，需要根据该方法返回值来依次执行
	 * 数值越小优先级越高
	 */
	@Override
	public int filterOrder() {
		return 0;
	}
	/**
	 *过滤器类型，决定过滤器的请求在哪个生命周期执行，pre代表会在请求被路由之前执行
	 *routing:在路由请求是被调用
	 *post:在routing和error过滤器之后被调用
	 *error:处理请求出错时调用
	 */
	@Override
	public String filterType() {
		return "pre";
	}

}
